import { CSSProperties, useState, FC, ReactNode, useRef, useEffect, useCallback } from "react"

const ScreenAdapter: FC<{
  width?: number // 设计稿
  height?: number
  children?: ReactNode
}> = (props) => {
  const { width = 1920, height = 1080 } = props
  
  const [styles, setStyles] = useState<CSSProperties>({
    width: width + 'px',
    height: height + 'px',
    transform: `scale(1)`,
    transformOrigin: `0 0`,
    transition: `0.3s`
  }),
  wrapper = useRef<HTMLDivElement | null>(null)

  const getParentStyle = (ele: HTMLDivElement) => {
    const parent = ele.parentElement

    const width = parent?.offsetWidth || 1920,
      height = parent?.offsetHeight || 1080

    return {
      width,
      height
    }
  }

  const setScale = useCallback(() => {
    const { width: pWidth, height: pHeight } = getParentStyle(wrapper.current!)

    const scaleX = pWidth / width,
      scaleY = pHeight / height
    
    setStyles((origin) => ({
      ...origin,
      transform: `scale(${scaleX}, ${scaleY})`
    }))
  }, [width, height])

  useEffect(() => {
    setScale()
    window.addEventListener('resize', setScale, false)

    return () => window.removeEventListener('resize', setScale, false)
  }, [setScale])

  return (
    <div ref={wrapper} style={{ ...styles }}>
      {props.children}
    </div>
  )
}

export default ScreenAdapter